import { onMounted, onUnmounted } from 'vue';

const EVENT_NAME = 'global-search';

export interface GlobalSearchPayload {
  keyword: string;
}

export function useGlobalSearch() {
  const emitSearch = (keyword: string) => {
    const payload: GlobalSearchPayload = { keyword };
    window.dispatchEvent(new CustomEvent<GlobalSearchPayload>(EVENT_NAME, { detail: payload } as CustomEventInit<GlobalSearchPayload>));
  };

  const onSearch = (handler: (keyword: string) => void) => {
    const listener = (e: Event) => {
      const ce = e as CustomEvent<GlobalSearchPayload>;
      handler(ce.detail?.keyword ?? '');
    };
    onMounted(() => window.addEventListener(EVENT_NAME, listener as EventListener));
    onUnmounted(() => window.removeEventListener(EVENT_NAME, listener as EventListener));
  };

  return { emitSearch, onSearch, EVENT_NAME };
}
